<?php
namespace app\model;
use app\BaseModel;

use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use think\Image;
use think\model\concern\SoftDelete;

use Endroid\QrCode\Color\Color;

use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;


use think\Session;
class Member extends BaseModel
{

    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = '0000-00-00 00:00:00';
    protected $hidden = ['update_time','delete_time','sort'];
    protected $append = ['ids','invite_url','invite_qrcode','invite_image','date_time','ago_time','level_name'];

    /**
     * 搜索器
     * title多字段搜索器
     */
    public function searchTitleAttr($query, $value, $data)
    {
        if (!empty($value)) {
            $query->where('mobile|name|invite_code|city', 'like', '%' . $value . '%');
        }
    }

    public function searchLevelIdAttr($query, $value, $data)
    {
        if ($value != -1) {
            $query->where('level_id', '=', $value );
        }
    }

    public static function onAfterInsert($data)
    {
        self::where('id', $data['id'])->update(['invite_code' => self::numStr(self::class)]);
    }

    public function setParentIdAttr($value, $data)
    {
        if (isset($data['parent_id'])) {
            $this->set('parent_invite_code',self::where('id',$value)->value('invite_code'));
            $this->set('parent_mobile',self::where('id',$value)->value('mobile'));
            return $value;
        }
    }

    /**
     * idStr
     * 根据会员ID生成字符串
     */
    public static function idStr($member_id, $str_length = 6)
    {
//        $str_length = 6;
//        $member_id = 132;
        $member_id_length = strlen($member_id);
        $member_arg = str_split($member_id);

        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $password = '';
        for ($i = 0; $i < $str_length - $member_id_length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        $new_str = $password . $member_id;
        $new_str = str_shuffle($new_str);
        $new_str_arg = str_split($new_str);
        $str = '';
        $kk = 0;
        foreach ($new_str_arg as $v) {
            if (is_numeric($v)) {
                $s = $member_arg[$kk];
                $kk++;
            } else {
                $s = $v;
            }
            $str .= $s;
        }
        return $str;
    }

    public static function numStr($model)
    {

        $mk_num = mt_rand(10000000,99999999);

        $find =$model::where('invite_code',$mk_num)->find();

        while (!empty($find)){
            $mk_num = mt_rand(10000000,99999999);
            $find = $model::where('invite_code',$mk_num)->find();
            // dump($mk_num);
            //Db::name('num')->insert(['title'=>$mk_num,'type'=>1]);
        }
        return $mk_num;
        echo 'res'.($mk_num);
        Db::name('num')->insert(['title'=>$mk_num,'type'=>2]);

    }

    public function getInviteUrlAttr($value,$data){
        if(!empty($data['invite_code'])) {
            return url('api/Member/web_register', ['invite_code' => $data['invite_code']], false, true)->build();
        }
    }

//    public function getInviteImageAttr($valur,$data){
//        return request()->domain().'/qrcode/'.$data['id'].'_image'.'.png?rand='.mt_rand(1000,9999);
//    }

//    public function getInviteQrcodeAttr($value, $data)
//    {
//        //return parent::getQrcodeAttr($value, $data); // TODO: Change the autogenerated stub
//        $id_image = './qrcode/'.$data['id'].'_image'.'.png';
//        if(file_exists($id_image) ===false){
//
//            $url = url('api/index/index',['invite_code' => $data['invite_code']],false,true)->build();
//            $result = Builder::create()
//                ->writer(new PngWriter())
//                ->writerOptions([])
//                ->data($url)
//                ->encoding(new Encoding('UTF-8'))
//                ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
//                ->size(300)
////           ->margin(40)
//                ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
////           ->logoPath(root_path().'/logo.png')
////            ->logoResizeToWidth(300)
//                ->labelText($data['invite_code'])
//                ->labelFont(new NotoSans(25))
////        ->labelAlignment(new LabelAlignmentCenter())
//                ->validateResult(false)
//                ->build()->saveToFile(root_path().'/public/qrcode/'.$data['id'].'.png');
//
//            $image = \think\Image::open('./bg.png');
//            $width =  $image->width();//背景图
//            $witch2 = \think\Image::open('./qrcode/'.$data['id'].'.png')->width();//二维码
//            $with = ($width-$witch2)/2;
//
//            $image->water('./qrcode/'.$data['id'].'.png',[$with,780])->save($id_image);
//        }
//
//
//        return request()->domain().'/qrcode/'.$data['id'].'.png';
////        $strPath = public_path().'/bg.png';  //背景图片物理路径
////        $strQrcodePath = '/qrcode/'.$data['id'].'.png';  //二维码图片物理路径
//        //创建图片对象
////        $backImg = imagecreatefromjpeg($strPath);
////        $qrcodeImg = imagecreatefrompng($strQrcodePath);
////
////        //合成图片
////        imagecopymerge($backImg, $qrcodeImg, 100,100,0,0,imagesx($qrcodeImg), imagesy($qrcodeImg), 100);
////
////        $strQrcodeBackPath = public_path().$data['id'].'.png';
////        //输出合成图片
////        imagepng($backImg, $strQrcodeBackPath);
////        $qrCode = QrCode::create('https://www.itqaq.com')
////            // 内容编码
////            ->setEncoding(new Encoding('UTF-8'))
////            // 容错等级
////            ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
////            // 内容区域大小
////            ->setSize(300)
////            // 内容区域外边距
////            ->setMargin(10)
////            // 内容圆形块尺寸模型
////            ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
////            // 内容颜色
////            ->setForegroundColor(new Color(0, 0, 0))
////            // 背景颜色
////            ->setBackgroundColor(new Color(255, 255, 255));
////// 二维码logo logo
////        $logo = Logo::create(__DIR__ . '/3.png')
////            ->setResizeToWidth(50);
////// 二维码下方文字 label
////        $label = Label::create('Label')
////            ->setTextColor(new Color(255, 0, 0));
////// 生成二维码数据对象(后面两个参数都是可选的)
////
////        if(!empty($data['invite_code'])){
////
//////            $url = url('api/Member/web_register',['invite_code' => $data['invite_code']],false,true)->build();
////
////
//          // return qrcode($url,'/'.$data['id'].'.png')['url'];
//        return request()->domain().'/qrcode/'.$data['id'].'.png';
////        }
//
//    }

//    public function getInviteQrcodeAttr($value, $data){
//        return request()->domain().'/qrcode/'.$data['id'].'.png';
//    }

    protected function getLevelNameAttr($value, $data){


        if(isset($data['level_id'])){
            $status = [0=>'游客',1=>'会员',2=>'经销商',3=>'总代理'];
            return $status[$data['level_id']];
        }

    }

//    protected function getLevelNameAttr($value, $data){
//
//        $name = '请后台设置级别';
//        $exp = self::where('id',$data['id'])->value('exp');
//        $where = [
//            ['min','<=',$exp],
//            ['max','>',$exp],
//        ];
//        $title = MemberLevel::where($where)->value('title');
//        return $title;
//    }

//    public function Son()
//    {
//        return $this->hasMany('Member', 'parent_id', 'id');
//    }
//
//







}